package eo.builder.impl;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

import eo.builder.URLVisitor;
import eo.builder.util.IterationStep;

/**
 * {@link URLVisitor} that visits only directories.
 * 
 * @author takeshi
 * 
 */
public class DirectoryURLVisitor extends AbstractURLVisitor implements
		URLVisitor {

	public boolean canResolve(URL url) {
		if (url == null) {
			return false;
		}
		if (!"file".equals(url.getProtocol())) {
			return false;
		}
		return url.getPath().endsWith("/");
		// directory
	}

	public void iterate(IterationStep<String> iteration, URL url)
			throws IOException {
		try {
			File root = new File(url.toURI());
			this.doIterateFiles(root, iteration);
		} catch (URISyntaxException e) {
			throw new IllegalArgumentException("URL not supported: " + url, e);
		}
	}

	private boolean doIterateFiles(final File root,
			final IterationStep<String> iteration) {
		if (!iteration.nextIteration(root.getName())) {
			return false;
		}
		if (root.isDirectory()) {
			File[] files = root.listFiles();
			for (File file : files) {
				if (!this.doIterateFiles(file, iteration)) {
					return false;
				}
			}
		}
		return true;
	}

}
